import React, { Component } from 'react'
import bases from './Data'
import './App8.css'
export default class App8 extends Component {
    constructor(props) {
        super(props)
    
        this.state = {
             bases,
             current:bases[0]
        }
    }
    _select=base=>{
        this.setState({current:base})
    }
    _del=item=>{
        let current=this.state.current
        let index=current.state.items.indexOf(item)
        current.items.splice(index,1)
        this.setState({current:current})
    }
    _idSort=()=>{
        let current=this.state.current
        if(this.idAsc){
            current.items.sort((a,b)=>b.id-a.id)
        }
        else{
            current.items.sort((a,b)=>a.id-b.id)
        }
        this.idAsc=!this.idAsc
        this.setState({current})
    }
    _nameSort=()=>{
        let current=this.state.current
        if(this.nameAsc){
            current.items.sort((a,b)=>a.name.localeCompare(b.name))
        }
        else{
            current.items.sort((a,b)=>b.name.localeCompare(a.name))
        }
        this.nameAsc=!this.nameAsc
        this.setState({current})
    }
    render() {
        return (
            <div id='container'>
                <aside>
                    {this.state.bases.map(base=>{
                        return <li className={base==this.state.current?"current":""}onClick={()=>this._select(base)}>{base.basename}</li>
                    })}
                </aside>
                <main></main>
                    <header>
                        {this.state.current.items.map(item=>{
                            return <div className='item'>
                                <h3>{item.name}</h3>
                                <h4>{item.count}</h4>
                                <p>
                                    <a href='#'>详细信息</a>
                                </p>
                                <p>
                                    <a onClick={()=>this._del(item)} href='#'>删除</a>
                                </p>
                            </div>
                        })}
                    </header>
                    <div id='content'>
                        <table>
                            <tr><th onClick={this._idSort}>id</th>
                            <th onClick={this._nameSort}>商品数量</th>
                            <th>操作</th>
                            </tr>
                            {this.state.current.items.map(item=>{
                                return <tr>
                                    <td>{item.id}</td>
                                    <td>{item.name}</td>
                                    <td>{item.count}</td>
                                    <td><button onClick={()=>this._del(item)}>删除</button></td>
                                    </tr>
                            })}
                        </table>
                    </div>                
            </div>
        )
    }
}
